package com.project.util;

import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: AddCookies <br/>
 * Description: <br/>
 * date: 2018/12/27 8:54<br/>
 *
 * @author lenovo<br />
 * @since JDK 1.8
 */
@Component
public class AddCookies {

    /**
     * Description: 向response中添加cookie<br/>
     * @author: lenovo<br/>
     * @date: 2018/12/27 15:05<br/>
     * @param:<br/>
     * @return:
     */
    public void  setCookie(HttpServletResponse response, Map<String , Object> map,HttpServletRequest request){
        for (String s: map.keySet()) {
            Cookie cookie = new Cookie(s,map.get(s)+"");
            response.addCookie(cookie);
        }
        for (Cookie cookie : request.getCookies()) {
            response.addCookie(cookie);
        }
    }

    /**
     * Description: 从request中获取cookie的值 <br/>
     * @author: lenovo<br/>
     * @date: 2018/12/27 15:06<br/>
     * @param:<br/>
     * @return:
     */
    public Map<String , String>  getCookie(HttpServletRequest request){

        Map<String,String> map = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            map.put(cookie.getName(),cookie.getValue());
        }

        return  map;
    }

    public void remove(HttpServletRequest request){

        Cookie [] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            cookie.setMaxAge(0);
        }
    }
}
